document.addEventListener('DOMContentLoaded', function() {
    const exportBtn = document.getElementById('exportBtn');
    const status = document.getElementById('status');
    const statusIcon = status.querySelector('.status-icon');
    const statusText = status.querySelector('.status-text');
    
    // 自动导出相关元素
    const autoExportEnabled = document.getElementById('autoExportEnabled');
    const exportInterval = document.getElementById('exportInterval');
    const intervalSetting = document.getElementById('intervalSetting');
    const autoExportStatus = document.getElementById('autoExportStatus');
    const nextExportTime = document.getElementById('nextExportTime');
    const testAutoExport = document.getElementById('testAutoExport');
    const resetAutoExport = document.getElementById('resetAutoExport');
    const testRefresh = document.getElementById('testRefresh');
    const testTimer = document.getElementById('testTimer');
    const testConnection = document.getElementById('testConnection');

    // 更新状态显示
    function updateStatus(icon, text, type = '') {
        statusIcon.textContent = icon;
        statusText.textContent = text;
        status.className = `status ${type}`;
    }

    // 配置管理
    const defaultConfig = {
        autoExportEnabled: false,
        exportInterval: 120 // 默认2小时
    };

    // 加载配置
    function loadConfig() {
        chrome.storage.sync.get(defaultConfig, function(config) {
            autoExportEnabled.checked = config.autoExportEnabled;
            exportInterval.value = config.exportInterval;
            updateAutoExportUI();
        });
    }

    // 保存配置
    function saveConfig() {
        const config = {
            autoExportEnabled: autoExportEnabled.checked,
            exportInterval: parseInt(exportInterval.value)
        };
        console.log('准备保存配置:', config);
        chrome.storage.sync.set(config, function() {
            console.log('配置已保存到storage:', config);
            // 通知background script配置已更改
            console.log('通知background script配置更改');
            chrome.runtime.sendMessage({
                action: 'updateAutoExportConfig',
                config: config
            }, function(response) {
                console.log('background script响应:', response);
            });
            // 更新显示
            updateNextExportTime();
        });
    }

    // 更新自动导出UI
    function updateAutoExportUI() {
        const isEnabled = autoExportEnabled.checked;
        intervalSetting.style.display = isEnabled ? 'flex' : 'none';
        testAutoExport.style.display = isEnabled ? 'flex' : 'none';
        resetAutoExport.style.display = isEnabled ? 'flex' : 'none';
        testRefresh.style.display = isEnabled ? 'flex' : 'none';
        testTimer.style.display = isEnabled ? 'flex' : 'none';
        
        if (isEnabled) {
            autoExportStatus.querySelector('.status-text').textContent = '自动刷新已启用';
            // 延迟一点时间确保DOM更新完成
            setTimeout(updateNextExportTime, 100);
        } else {
            autoExportStatus.querySelector('.status-text').textContent = '自动刷新已禁用';
            nextExportTime.textContent = '';
        }
    }

    // 更新下次导出时间显示
    function updateNextExportTime() {
        chrome.storage.local.get(['lastExportTime', 'exportInterval'], function(data) {
            const now = new Date();
            let intervalMinutes = data.exportInterval;
            
            // 如果没有存储的间隔，从当前配置获取
            if (!intervalMinutes) {
                intervalMinutes = parseInt(exportInterval.value) || 120;
            }
            
            if (data.lastExportTime) {
                // 有历史导出时间，计算下次导出时间
                const nextTime = new Date(data.lastExportTime + intervalMinutes * 60 * 1000);
                const diff = nextTime - now;
                
                if (diff > 0) {
                    const hours = Math.floor(diff / (1000 * 60 * 60));
                    const minutes = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                    const seconds = Math.floor((diff % (1000 * 60)) / 1000);
                    
                    if (hours > 0) {
                        nextExportTime.textContent = `下次刷新: ${hours}小时${minutes}分${seconds}秒`;
                    } else if (minutes > 0) {
                        nextExportTime.textContent = `下次刷新: ${minutes}分${seconds}秒`;
                    } else {
                        nextExportTime.textContent = `下次刷新: ${seconds}秒`;
                    }
                } else {
                    nextExportTime.textContent = '即将刷新...';
                }
            } else {
                // 没有历史导出时间，显示当前间隔
                const hours = Math.floor(intervalMinutes / 60);
                const minutes = intervalMinutes % 60;
                if (hours > 0) {
                    nextExportTime.textContent = `将在${hours}小时${minutes}分钟后首次刷新`;
                } else {
                    nextExportTime.textContent = `将在${minutes}分钟后首次刷新`;
                }
            }
        });
    }

    // 检查是否在YouTube网站
    function checkYouTubeSite() {
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            const currentTab = tabs[0];
            if (currentTab && currentTab.url) {
                const url = currentTab.url;
                if (url.includes('youtube.com') || url.includes('youtube-nocookie.com')) {
                    updateStatus('✅', '检测到YouTube网站', 'success');
                    exportBtn.disabled = false;
                    
                    // 测试cookie获取
                    testCookieAccess();
                } else {
                    updateStatus('⚠️', '请在YouTube网站上使用', 'error');
                    exportBtn.disabled = true;
                }
            } else {
                updateStatus('❌', '无法获取当前页面', 'error');
                exportBtn.disabled = true;
            }
        });
    }
    
    // 测试cookie访问权限
    function testCookieAccess() {
        chrome.cookies.getAll({}, function(cookies) {
            if (chrome.runtime.lastError) {
                console.log('Cookie访问测试失败:', chrome.runtime.lastError);
                updateStatus('❌', 'Cookie访问权限不足', 'error');
                exportBtn.disabled = true;
            } else {
                console.log('Cookie访问测试成功，找到', cookies.length, '个cookie');
                const youtubeCookies = cookies.filter(cookie => 
                    cookie.domain.includes('youtube.com') || cookie.domain.includes('youtube-nocookie.com')
                );
                console.log('其中YouTube相关cookie:', youtubeCookies.length, '个');
            }
        });
    }

    // 导出Cookie
    function exportCookies() {
        updateStatus('⏳', '正在导出Cookie...', 'loading');
        exportBtn.disabled = true;

        // 获取当前标签页的URL
        chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
            const currentTab = tabs[0];
            if (!currentTab || !currentTab.url) {
                updateStatus('❌', '无法获取当前页面', 'error');
                exportBtn.disabled = false;
                return;
            }

            const url = new URL(currentTab.url);
            const domain = url.hostname;

            // 先尝试获取所有cookies，然后过滤YouTube相关的
            chrome.cookies.getAll({}, function(allCookies) {
                if (chrome.runtime.lastError) {
                    updateStatus('❌', '获取Cookie失败: ' + chrome.runtime.lastError.message, 'error');
                    exportBtn.disabled = false;
                    return;
                }
                
                console.log(`总共找到 ${allCookies.length} 个cookie`);
                
                // 过滤YouTube相关的cookies
                const youtubeCookies = allCookies.filter(cookie => {
                    return cookie.domain.includes('youtube.com') || 
                           cookie.domain.includes('youtube-nocookie.com') ||
                           cookie.domain.includes('google.com') ||
                           cookie.domain.includes('googleapis.com');
                });
                
                console.log(`其中YouTube相关cookie: ${youtubeCookies.length} 个`);
                
                if (youtubeCookies.length === 0) {
                    updateStatus('⚠️', '未找到任何YouTube相关Cookie', 'error');
                    exportBtn.disabled = false;
                    return;
                }
                
                // 去重cookies（基于name和domain）
                const uniqueCookies = [];
                const seen = new Set();
                
                youtubeCookies.forEach(cookie => {
                    const key = `${cookie.name}-${cookie.domain}`;
                    if (!seen.has(key)) {
                        seen.add(key);
                        uniqueCookies.push(cookie);
                    }
                });
                
                console.log(`去重后: ${uniqueCookies.length} 个cookie`);
                
                // 生成Netscape格式的cookie文件
                const netscapeContent = generateNetscapeFormat(uniqueCookies, domain);
                
                // 创建并下载文件
                const blob = new Blob([netscapeContent], { type: 'text/plain' });
                const url = URL.createObjectURL(blob);
                
                const now = new Date();
                const timestamp = now.toISOString().slice(0, 19).replace(/:/g, '-').replace('T', '_');
                chrome.downloads.download({
                    url: url,
                    filename: `youtube_cookies_${timestamp}.txt`,
                    saveAs: true
                }, function(downloadId) {
                    if (chrome.runtime.lastError) {
                        updateStatus('❌', '下载失败: ' + chrome.runtime.lastError.message, 'error');
                    } else {
                        updateStatus('✅', `成功导出${uniqueCookies.length}个Cookie`, 'success');
                    }
                    exportBtn.disabled = false;
                });
            });
        });
    }

    // 生成Netscape格式的cookie内容
    function generateNetscapeFormat(cookies, domain) {
        let content = '# Netscape HTTP Cookie File\n';
        content += '# This is a generated file! Do not edit.\n\n';
        
        cookies.forEach(cookie => {
            const domain = cookie.domain.startsWith('.') ? cookie.domain : '.' + cookie.domain;
            const path = cookie.path || '/';
            const secure = cookie.secure ? 'TRUE' : 'FALSE';
            const expires = cookie.expirationDate ? Math.floor(cookie.expirationDate) : '0';
            const name = cookie.name;
            const value = cookie.value;
            
            content += `${domain}\t${domain.includes('.') ? 'TRUE' : 'FALSE'}\t${path}\t${secure}\t${expires}\t${name}\t${value}\n`;
        });
        
        return content;
    }

    // 绑定事件
    exportBtn.addEventListener('click', exportCookies);
    
    // 自动导出事件监听
    autoExportEnabled.addEventListener('change', function() {
        updateAutoExportUI();
        saveConfig();
    });
    
    exportInterval.addEventListener('change', function() {
        saveConfig();
    });
    
    // 测试自动刷新按钮
    testAutoExport.addEventListener('click', function() {
        updateStatus('⏳', '正在测试自动刷新...', 'loading');
        chrome.runtime.sendMessage({
            action: 'testAutoRefresh'
        }, function(response) {
            if (response && response.success) {
                updateStatus('✅', '测试自动刷新完成', 'success');
            } else {
                updateStatus('❌', '测试自动刷新失败', 'error');
            }
        });
    });
    
    // 重置自动导出状态按钮
    resetAutoExport.addEventListener('click', function() {
        updateStatus('⏳', '正在重置状态...', 'loading');
        chrome.runtime.sendMessage({
            action: 'resetAutoExport'
        }, function(response) {
            if (response && response.success) {
                updateStatus('✅', '状态已重置', 'success');
                updateNextExportTime();
            } else {
                updateStatus('❌', '重置失败', 'error');
            }
        });
    });
    
    // 测试刷新按钮
    testRefresh.addEventListener('click', function() {
        updateStatus('⏳', '正在测试刷新...', 'loading');
        chrome.runtime.sendMessage({
            action: 'testRefresh'
        }, function(response) {
            if (response && response.success) {
                updateStatus('✅', '刷新测试成功', 'success');
            } else {
                updateStatus('❌', '刷新测试失败: ' + (response?.error || '未知错误'), 'error');
            }
        });
    });
    
    // 测试定时器按钮
    testTimer.addEventListener('click', function() {
        updateStatus('⏳', '正在测试定时器...', 'loading');
        chrome.runtime.sendMessage({
            action: 'testTimer'
        }, function(response) {
            if (response && response.success) {
                updateStatus('✅', '定时器测试已启动，请查看控制台', 'success');
            } else {
                updateStatus('❌', '定时器测试失败', 'error');
            }
        });
    });

    // 测试连接按钮事件
    testConnection.addEventListener('click', function() {
        console.log('点击测试连接按钮');
        updateStatus('⏳', '测试连接中...', 'testing');
        
        chrome.runtime.sendMessage({action: 'ping'}, function(response) {
            if (chrome.runtime.lastError) {
                console.error('Background script连接失败:', chrome.runtime.lastError.message);
                updateStatus('❌', 'Background连接失败', 'error');
            } else {
                console.log('Background script连接成功:', response);
                updateStatus('✅', 'Background连接正常', 'success');
                setTimeout(() => updateStatus('⏳', '准备就绪'), 3000);
            }
        });
    });

    // 测试background script连接
    function testBackgroundConnection() {
        console.log('测试background script连接...');
        chrome.runtime.sendMessage({action: 'ping'}, function(response) {
            if (chrome.runtime.lastError) {
                console.error('Background script连接失败:', chrome.runtime.lastError.message);
            } else {
                console.log('Background script连接成功:', response);
            }
        });
    }

    // 初始化
    loadConfig();
    checkYouTubeSite();
    testBackgroundConnection();
    
    // 定期更新下次导出时间显示
    setInterval(updateNextExportTime, 1000); // 每秒更新一次
});
